import {useRoute} from "vue-router";
import {useLoginStore} from "@/store/usersLoginStore.ts";
import {useBreadcrumbStore} from "@/store/breadcrumbStroe.ts";

export default function () {
    interface MenuItem {
        id: number;
        path: string;
        name: string;
        redirect: string;
        component: string;
        meta: {
            title: string;
            icon: string;
        };
        children: MenuItem[];
    }

    enum MenuIcon {
        HomeFilled = IconEpHomeFilled,
        Lock = IconEpLock,
        Goods = IconEpGoods,
        User = IconEpUser,
        Avatar = IconEpAvatar,
        UserFilled = IconEpUserFilled,
        Tickets = IconEpTickets,
        ShoppingBag = IconEpShoppingBag,
        PriceTag = IconEpPriceTag,
        Sell = IconEpSell,
        SoldOut = IconEpSoldOut,
    }

    const breadcrumb = useBreadcrumbStore()
    const LoginStore = useLoginStore()
    const $route = useRoute()
    let isShow = ref(false)
    // const breadcrumbData = reactive<MenuItem[]>([]);
    const changeIcon = () => {
        LoginStore.isCollapse = !LoginStore.isCollapse
        isShow.value = !isShow.value
    }

    function getString(icon: string): MenuIcon {
        return MenuIcon[icon as keyof typeof MenuIcon];
    }

    //  根据菜单赛选面包屑数据
    const generateBreadcrumbs = (path: string): MenuItem[] => {
        const breadcrumbs: MenuItem[] = [];
        const findBreadcrumbs = (menus: MenuItem[], pathSegments: string[]) => {
            for (const menu of menus) {
                const currentPath = `/${pathSegments.join('/')}`;
                if (menu.path === currentPath) {
                    breadcrumbs.push(menu);
                    if (menu.children.length > 0 && pathSegments.length > 1) {
                        pathSegments.shift();
                        findBreadcrumbs(menu.children, pathSegments);
                    }
                    break;
                } else if (menu.children.length > 0) {
                    findBreadcrumbs(menu.children, pathSegments);
                    if (breadcrumbs.length > 0) {
                        breadcrumbs.unshift(menu);
                        break;
                    }
                }
            }
        };
        const pathSegments = path.split('/').filter(segment => segment);
        findBreadcrumbs(LoginStore.$state.menus, pathSegments);
        return breadcrumbs;
    };

    watch(() => $route.path, (newPath) => {
        const newBreadcrumbs = generateBreadcrumbs(newPath);
        breadcrumb.breadcrumbData.splice(0, breadcrumb.breadcrumbData.length, ...newBreadcrumbs);
    }, {immediate: true});
    // 监听面包屑数据的变化，控制显示或隐藏
    return {isShow, changeIcon, getString, breadcrumb}
}